package com.hy.businesss.service.impl;

import com.hy.businesss.domain.Result;
import com.hy.businesss.service.BusinessServiceXA;
import com.hy.businesss.feign.OrderClient;
import com.hy.businesss.feign.StorageClient;
import io.seata.core.context.RootContext;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;



@Service
public class BusinessServiceImplXA implements BusinessServiceXA {


    @Autowired
    StorageClient storageClient;

    @Autowired
    OrderClient orderClient;

    @GlobalTransactional
    public Result operateByXA(long userId, long productId) {
        String xid = RootContext.getXID();

        System.out.println("New Transaction Begins: " + xid);

        String orderRes = orderClient.createXAOrder(userId, productId);
        if (!orderRes.equals("success")){
            throw new RuntimeException("创建订单服务出错！");
        }
        boolean storageRes = storageClient.changeXaStorage(userId, 1);
        if (!storageRes){
            throw new RuntimeException("扣减库存服务出错！");
        }

        // 测试 异常
        //int i = 1/0;

        return new Result(HttpStatus.OK.value(), "ok","查询成功！");
    }
}
